/* eslint-disable react/prop-types */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-use-before-define */
import { DictValueEnum } from "@/components/DictTag";
import { getDict } from "@/services/api/module/system/dict";
import { options } from "@/services/api/module/tenant/tenant/package";
import { getTenant } from "@/services/api/module/tenant/tenant/tenants";
import {
	DrawerForm,
	ModalForm,
	ProForm,
	ProFormDateTimePicker,
	ProFormDigit,
	ProFormInstance,
	ProFormRadio,
	ProFormSelect,
	ProFormText,
	ProFormTextArea,
	ProFormUploadButton,
	StepsForm
} from "@ant-design/pro-components";
import { Modal, Image, Tooltip, Typography, message, Upload, Result, Button, GetProp, UploadProps, UploadFile } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { save } from "@/services/api/module/tenant/tenant/tenants";
import { genUCC } from "@/services/api/Tools";
export type TenantFormData = Record<string, unknown> & Partial<API.Tenant.TenantBo>;
export type TenantFormProps = {
	onCancel: () => void;
	open: boolean;
	id: number | undefined;
	statusOptions: DictValueEnum;
	industryOptions: DictValueEnum;
	scaleOptions: DictValueEnum;
	onRefresh: () => void;
};
type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];

const getBase64 = (file: FileType): Promise<string> =>
	new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result as string);
		reader.onerror = error => reject(error);
	});
const TenantForm: React.FC<TenantFormProps> = props => {
	// 国际化
	const oneFormRef = useRef();
	const formRef = useRef<ProFormInstance>();
	const title = "创建租户";
	const { statusOptions, id, open, onRefresh, onCancel, industryOptions, scaleOptions } = props;
	const [tenantId, setTenantId] = useState(undefined);
	const [previewOpen, setPreviewOpen] = useState(false);
	const [previewImage, setPreviewImage] = useState();
	const [isFinsh, setIsFinsh] = useState(false);
	const [registerMsg, setRegisterMsg] = useState("");
	const [registerTitle, setRegisterTitle] = useState("");
	const [current, setCurrent] = useState(0);
	// 初始化
	useEffect(() => {
		formRef?.current?.resetFields();
	}, [id]);
	// 关闭
	const handleCancel = () => {
		setTenantId(undefined);
		formRef.current?.resetFields();
		setCurrent(0);
		setIsFinsh(false);
		onCancel();
	};
	// 表单提交
	const handleFinish = async (values: Record<string, any>) => {
		const logo = await getBase64(values.logo[0]?.originFileObj);
		const valueData = { ...values };
		valueData.logo = logo;
		return new Promise<boolean>((resolve, reject) => {
			save(valueData)
				.then(res => {
					setIsFinsh(true);
					setRegisterMsg(res?.data);
					setRegisterTitle(res?.msg);
					onRefresh();
					resolve(true);
				})
				.catch(err => {
					reject(false);
				});
		});
	};

	const handlePreview = async (file: UploadFile) => {
		if (!file.url && !file.preview) {
			file.preview = await getBase64(file.originFileObj as FileType);
		}
		// @ts-ignore
		setPreviewImage(file.url || (file.preview as string));
		setPreviewOpen(true);
	};

	const generatedUcc = () => {
		genUCC().then((data: any) => {
			// @ts-ignore
			oneFormRef?.current?.setFieldsValue({ licenseNumber: data });
		});
	};
	return (
		<StepsForm<TenantFormData>
			formRef={formRef}
			stepsProps={{
				type: "navigation"
			}}
			current={current}
			onCurrentChange={_ => {
				setCurrent(_);
			}}
			onFinish={handleFinish}
			stepsFormRender={(dom, submitter) => {
				return (
					<Modal
						title={title}
						width={900}
						centered
						onCancel={handleCancel}
						open={open}
						footer={() => {
							return <>{!isFinsh ? submitter : <Button onClick={handleCancel}>关闭</Button>}</>;
						}}
						destroyOnClose
					>
						{!isFinsh && dom}
						{isFinsh && (
							<Result
								status="success"
								title={registerTitle}
								subTitle={registerMsg}
								// subTitle="公司：智能融合合集有限公司（Smart Fusion）,完成注册，公司编号: 2017182818828182881"
							/>
						)}
						{/* <Result
							status="success"
							title="注册完成"
							subTitle="公司：智能融合合集有限公司（Smart Fusion）,完成注册，公司编号: 2017182818828182881"
						/> */}
					</Modal>
				);
			}}
		>
			<StepsForm.StepForm<TenantFormData>
				formRef={oneFormRef}
				name="base"
				title="基础信息"
				onFinish={async () => {
					return true;
				}}
			>
				<ProFormUploadButton
					required
					listType="picture-card"
					label="LOGO"
					max={1}
					rules={[
						{
							required: true,
							message: "请上传文件"
						}
					]}
					accept=".png,.jpg,.jpeg,.gif,.svg"
					extra={
						<Typography.Text type="secondary">
							请上传大小不超过 5MB 的文件{" "}
							<Tooltip placement="top" title={`.png, .jpg, .jpeg, .gif, .svg`}>
								<Typography.Link>查看格式要求</Typography.Link>
							</Tooltip>
						</Typography.Text>
					}
					fieldProps={{
						onPreview: file => handlePreview(file),
						maxCount: 1,
						beforeUpload: file => {
							const isImage = file.type.includes("image/");
							const isAcceptedType = [".png", ".jpg", ".jpeg", ".gif", ".svg"].some(ext => file.name.toLowerCase().endsWith(ext));
							if (!isImage || !isAcceptedType) {
								message.error("只能上传图片文件！");
								return Upload.LIST_IGNORE;
							}
							return false;
						}
					}}
					name="logo"
				/>

				<ProForm.Group>
					<ProFormText
						width="md"
						name="companyName"
						label="企业名称"
						placeholder="请输入企业名称"
						rules={[
							{
								required: true,
								message: "请输入企业名称"
							}
						]}
					/>
					<ProFormSelect
						width="sm"
						label="行业"
						valueEnum={industryOptions}
						name="industry"
						rules={[
							{
								required: true,
								message: "请选择行业"
							}
						]}
					/>
					<ProFormSelect
						width="sm"
						label="规模"
						valueEnum={scaleOptions}
						name="scale"
						rules={[
							{
								required: true,
								message: "请选择规模"
							}
						]}
					/>
				</ProForm.Group>
				<ProForm.Group>
					<ProFormText
						width="md"
						name="licenseNumber"
						fieldProps={{
							suffix: (
								<Button type="link" size="small" onClick={generatedUcc}>
									生成
								</Button>
							)
						}}
						label="统一社会信用代码"
						rules={[
							{
								required: true,
								message: "请输入统一社会信用代码"
							}
						]}
						placeholder="请输入统一社会信用代码"
					/>
					<ProFormText
						width="sm"
						name="contactRealName"
						label="联系人"
						placeholder="请输入联系人"
						rules={[
							{
								required: true,
								message: "请输入联系人"
							}
						]}
					/>
					<ProFormText
						width="sm"
						name="contactPhone"
						label="联系人电话"
						placeholder="请输入联系人电话"
						rules={[
							{
								required: true,
								message: "请输入联系人电话"
							}
						]}
					/>
				</ProForm.Group>
				<ProForm.Group>
					<ProFormText
						width="sm"
						name="contactEmail"
						label="联系邮箱"
						placeholder="请输入联系邮箱"
						rules={[
							{
								required: true,
								message: "请输入联系邮箱"
							},
							{
								type: "email",
								message: "邮箱格式不正确"
							}
						]}
					/>
					<ProFormText
						width="sm"
						name="telephone"
						label="座机电话"
						placeholder="请输入联系邮箱"
						rules={[
							{
								required: true,
								message: "请输入联系邮箱"
							}
						]}
					/>
					<ProFormRadio.Group
						width="sm"
						valueEnum={statusOptions}
						name="status"
						radioType="button"
						label="状态"
						initialValue={"0"}
						placeholder="请选择状态"
						rules={[
							{
								required: true,
								message: "请选择状态"
							}
						]}
					/>
				</ProForm.Group>
				<ProFormText name="address" label="企业地址" placeholder="请输入企业地址" />
				<ProFormTextArea name="intro" label="企业简介" placeholder="请输入企业简介" />
			</StepsForm.StepForm>
			<StepsForm.StepForm name="admin" title="管理员信息">
				<ProForm.Group>
					<ProFormText
						width="md"
						name="contactUserName"
						label="租户管理员账号"
						placeholder="请输入租户管理员账号"
						rules={[
							{
								required: true,
								message: "请输入租户管理员账号"
							}
						]}
					/>
					<ProFormText.Password
						width="md"
						name="password"
						label="租户管理员密码"
						placeholder="请输入租户管理员密码"
						rules={[
							{
								required: true,
								message: "请输入租户管理员密码"
							}
						]}
					/>
				</ProForm.Group>
			</StepsForm.StepForm>
			<StepsForm.StepForm name="package" title="套餐信息">
				<ProForm.Group>
					<ProFormDateTimePicker width="md" name="expireTime" label="租户过期时间" placeholder="请选择租户过期时间" />
					<ProFormDigit
						width="md"
						name="accountCount"
						tooltip="-1代表无限制账号数量"
						label="账号数量"
						placeholder="请输入租户账号数量"
						min={-1}
						rules={[
							{
								required: true,
								message: "请输入租户账号数量"
							}
						]}
						initialValue={-1}
					/>
				</ProForm.Group>
				<ProForm.Group>
					<ProFormText width="md" name="domain" label="租户绑定域名" placeholder="请输入租户绑定域名" />
					<ProFormSelect
						width="md"
						name="packageId"
						label="租户套餐"
						request={() => {
							return options().then((res: any) => {
								return res.data;
							});
						}}
						rules={[
							{
								required: true,
								message: "请选择租户套餐"
							}
						]}
						fieldProps={{
							fieldNames: {
								label: "packageName",
								value: "id"
							}
						}}
						placeholder="租户套餐"
					/>
				</ProForm.Group>
			</StepsForm.StepForm>
			{previewImage && (
				<Image
					wrapperStyle={{ display: "none" }}
					preview={{
						visible: previewOpen,
						onVisibleChange: visible => setPreviewOpen(visible),
						afterOpenChange: visible => !visible && setPreviewImage(undefined)
					}}
					src={previewImage}
				/>
			)}
		</StepsForm>
	);
};

export default TenantForm;
